<template>
  <div class="bom-transfer">
    <el-row justify="center" class="w-full">
      <el-col :xs="24" :sm="24" :md="20" :lg="18" :xl="16">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <el-icon color="#F56C6C">
                <files />
              </el-icon>
              <span class="ml-2">Excel BOM 合并工具</span>
            </div>
          </template>

          <bom-processor
            ref="bomProcessorRef"
            :file="fileList[0]?.raw"
            :template-file="form.templateFile"
            :material-ref-file="form.materialRefFile"
            :top-nodes="form.topNodes"
            :split-size="form.splitSize"
            @progress="msg => logs.push(msg)"
            @error="err => logs.push(`错误: ${err}`)"
            @complete="data => logs.push(`生成${data.length}个文件`)"
          >
            <el-form :model="form" label-width="120px">
              <el-form-item label="源文件">
                <el-upload
                  class="upload-demo"
                  action=""
                  :auto-upload="false"
                  :on-change="handleFileChange"
                  :file-list="fileList"
                  accept=".xlsx,.xls"
                >
                  <el-button type="primary">选择文件</el-button>
                  <template #tip>
                    <div class="el-upload__tip">请上传包含BOM数据的Excel文件</div>
                  </template>
                </el-upload>
              </el-form-item>

              <el-form-item label="模板Excel文件" prop="templateFile">
                <el-upload
                  :auto-upload="false"
                  :limit="1"
                  :on-change="handleTemplateChange"
                  accept=".xlsx,.xls"
                >
                  <el-button type="primary">选择模板文件</el-button>
                </el-upload>
              </el-form-item>

              <el-form-item label="物料参考文件" prop="materialRefFile">
                <el-upload
                  :auto-upload="false"
                  :limit="1"
                  :on-change="handleMaterialRefChange"
                  accept=".xlsx,.xls"
                >
                  <el-button type="primary">选择物料参考文件</el-button>
                </el-upload>
              </el-form-item>
              <el-form-item label="顶节点筛选">
                <el-input
                  v-model="form.topNodes"
                  placeholder="输入顶节点物料编号，多个用逗号分隔"
                />
              </el-form-item>

              <el-form-item label="分割大小">
                <el-select v-model="form.splitSize" placeholder="请选择">
                  <el-option
                    v-for="item in splitOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>

              <el-form-item>
                <el-button type="primary" :loading="processing" @click="handleProcess">
                  开始处理
                </el-button>
              </el-form-item>
            </el-form>
          </bom-processor>

          <el-divider />

          <div class="log-container">
            <el-card shadow="never">
              <template #header>
                <div class="log-header">
                  <span>处理日志</span>
                  <el-button size="small" @click="clearLogs">清空日志</el-button>
                </div>
              </template>
              <div class="log-content">
                <div
                  v-for="(logBlock, blockIndex) in logBlocks"
                  :key="blockIndex"
                  class="log-block"
                >
                  <div class="log-block-header">第 {{ blockIndex + 1 }} 次执行</div>
                  <div v-for="(log, index) in logBlock" :key="index" class="log-item">
                    {{ log }}
                  </div>
                </div>
              </div>
            </el-card>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue';
import BomProcessor from '@/components/apps/bomTransfer/index.vue';
import { ElMessage } from 'element-plus';
import type { BomData } from '@/components/apps/bomTransfer/index.vue';

interface FormData {
  topNodes: string;
  splitSize: number;
  templateFile: File | null;
  materialRefFile: File | null;
}

const form = reactive<FormData>({
  topNodes: '',
  splitSize: 0,
  templateFile: null,
  materialRefFile: null
});

const fileList = ref([]);
const processing = ref(false);
const logs = ref<string[]>([]);
const logBlocks = ref<string[][]>([]);
const currentExecutionId = ref(0);

const splitOptions = [
  {
    value: 0,
    label: '不分割'
  },
  {
    value: 1000,
    label: '1000条/文件'
  },
  {
    value: 3000,
    label: '3000条/文件'
  },
  {
    value: 5000,
    label: '5000条/文件'
  },
  {
    value: 8000,
    label: '8000条/文件'
  },
  {
    value: 10000,
    label: '10000条/文件'
  }
];

const formatLogTime = () => {
  const now = new Date();
  return `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')} ${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}:${now.getSeconds().toString().padStart(2, '0')}`;
};

const addLog = (message: string) => {
  const timestamp = formatLogTime();
  logs.value.push(`[${timestamp}] ${message}`);
};

const handleFileChange = (file: any) => {
  fileList.value = [file];
  addLog(`已选择文件: ${file.name}`);
};

const handleTemplateChange = (file: any) => {
  form.templateFile = file.raw;
  addLog(`已选择模板文件: ${file.name}`);
};

const handleMaterialRefChange = (file: any) => {
  form.materialRefFile = file.raw;
  addLog(`已选择物料参考文件: ${file.name}`);
};

const bomProcessorRef = ref<InstanceType<typeof BomProcessor>>();

const clearLogs = () => {
  logs.value = [];
  logBlocks.value = [];
  currentExecutionId.value = 0;
};

const handleProcess = async () => {
  if (!fileList.value.length) {
    ElMessage.warning('请先上传文件');
    return;
  }

  if (!form.templateFile) {
    ElMessage.warning('请先选择模板文件');
    return;
  }

  processing.value = true;

  // 开始新的执行块
  currentExecutionId.value++;
  addLog(`开始第 ${currentExecutionId.value} 次处理BOM数据...`);

  try {
    await bomProcessorRef.value?.processBomData();
    addLog('数据处理完成');

    // 保存当前执行日志到分块
    if (logs.value.length > 0) {
      logBlocks.value.push([...logs.value]);
      logs.value = [];
    }

    ElMessage.success('处理完成');
  } catch (error) {
    addLog(`处理失败: ${error}`);

    // 保存当前执行日志到分块（包括错误信息）
    if (logs.value.length > 0) {
      logBlocks.value.push([...logs.value]);
      logs.value = [];
    }

    ElMessage.error('处理失败');
  } finally {
    processing.value = false;
  }
};
</script>

<style scoped>
.bom-transfer {
  width: 100%;
  padding: 20px;
}

:deep(.el-row) {
  width: 100%;
  margin: 0 !important;
}

.box-card {
  width: 100%;
}

.card-header {
  display: flex;
  align-items: center;
  font-size: 1.2em;
}

.ml-2 {
  margin-left: 0.5rem;
}

.mt-4 {
  margin-top: 1rem;
}

.w-full {
  width: 100%;
}

.log-container {
  margin-top: 1rem;
}

.log-header {
  font-weight: bold;
}

.log-content {
  max-height: 300px;
  overflow-y: auto;
}

.log-item {
  margin: 5px 0;
  font-size: 14px;
  padding: 8px;
  border-radius: 4px;
  background-color: var(--el-fill-color-blank);
  transition: background-color 0.2s;
}

.log-item:hover {
  background-color: var(--el-fill-color-light);
}

.log-block {
  margin-bottom: 16px;
  border: 1px solid var(--el-border-color);
  border-radius: 6px;
  overflow: hidden;
}

.log-block-header {
  background-color: var(--el-color-primary-light-9);
  padding: 8px 12px;
  font-weight: bold;
  color: var(--el-color-primary);
  border-bottom: 1px solid var(--el-border-color);
}

.log-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
